package com.vonchenchen.renderer;

import android.hardware.Camera;
import android.os.Build;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by  on 2021/1/27.
 */
public class DeviceUtils {
    public static final int DEVICE_INFO_UNKNOWN = -1;
    private static final String TAG = "DeviceUtils";
    private static final String[] H264_HW_BLACKLIST = new String[]{"SAMSUNG-SGH-I337", "Nexus 7", "Nexus 4", "P6-C00", "HM 2A", "XT105", "XT109", "XT1060"};
    private static final FileFilter CPU_FILTER = new FileFilter() {
        public boolean accept(File pathname) {
            String path = pathname.getName();
            if (path.startsWith("cpu")) {
                for(int i = 3; i < path.length(); ++i) {
                    if (!Character.isDigit(path.charAt(i))) {
                        return false;
                    }
                }

                return true;
            } else {
                return false;
            }
        }
    };

    public DeviceUtils() {
    }

    public static String getDeviceId() {
        String deviceId = Build.MANUFACTURER + "/" + Build.MODEL + "/" + Build.PRODUCT + "/" + Build.DEVICE + "/" + Build.VERSION.SDK_INT + "/" + System.getProperty("os.version");
        if (deviceId != null) {
            deviceId = deviceId.toLowerCase();
        }

        String bid = Build.ID;
        Pattern pattern = Pattern.compile(".*[A-Z][A-M][0-9]$");
        Matcher matcher = pattern.matcher(bid);
        if (Build.BRAND.toLowerCase().equals("samsung") && Build.DEVICE.toLowerCase().startsWith("cs02") && !matcher.find() && Build.VERSION.SDK_INT == 19) {
            deviceId = "yeshen/simulator/" + Build.MODEL + "/" + Build.PRODUCT + "/" + Build.DEVICE + "/" + Build.VERSION.SDK_INT + "/" + System.getProperty("os.version");
        }

        return deviceId;
    }

    public static String getDeviceInfo() {
        String deviceInfo = Build.MANUFACTURER + "/" + Build.MODEL;
        if (deviceInfo != null) {
            deviceInfo = deviceInfo.toLowerCase();
        }

        return deviceInfo;
    }

    public static String getSystemInfo() {
        String systemInfo = "Android/" + Build.VERSION.RELEASE;
        return systemInfo;
    }

    public static int selectFrontCamera() {
        int index = 0;

        try {
            index = Camera.getNumberOfCameras() > 1 ? 1 : 0;
        } catch (Exception var2) {
            Log.e("DeviceUtils", var2.toString());
        }

        return index;
    }

    public static int getNumberOfCameras() {
        try {
            return Camera.getNumberOfCameras();
        } catch (Exception var1) {
            Log.e("DeviceUtils", var1.toString());
            return 0;
        }
    }

    public static int getRecommendedEncoderType() {
        List<String> exceptionModels = Arrays.asList(H264_HW_BLACKLIST);
        if (exceptionModels.contains(Build.MODEL)) {
            Log.w("DeviceUtils", "Model: " + Build.MODEL + " has black listed H.264 encoder.");
            return 1;
        } else {
            return Build.VERSION.SDK_INT <= 18 ? 1 : 0;
        }
    }

    public static int getNumberOfCPUCores() {
        if (Build.VERSION.SDK_INT <= 10) {
            return 1;
        } else {
            int cores;
            try {
                cores = getCoresFromFileInfo("/sys/devices/system/cpu/possible");
                if (cores == -1) {
                    cores = getCoresFromFileInfo("/sys/devices/system/cpu/present");
                }

                if (cores == -1) {
                    cores = getCoresFromCPUFileList();
                }
            } catch (SecurityException var2) {
                cores = -1;
            } catch (NullPointerException var3) {
                cores = -1;
            }

            return cores;
        }
    }

    public static String getCpuName() {
        FileReader fr = null;

        try {
            fr = new FileReader("/proc/cpuinfo");
            BufferedReader br = new BufferedReader(fr);
            String text = br.readLine();
            String[] array = text.split(":\\s+", 2);

            for(int i = 0; i < array.length; ++i) {
            }

            if (fr != null) {
                fr.close();
            }

            String var19 = array[1];
            return var19;
        } catch (FileNotFoundException var16) {
            Log.e("DeviceUtils", "getCpuName failed, no /proc/cpuinfo found in system", var16);
        } catch (IOException var17) {
            Log.e("DeviceUtils", "getCpuName failed,", var17);
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException var15) {
                    Log.e("DeviceUtils", "failed to close proc file", var15);
                }
            }

        }

        return null;
    }

    public static String getCpuABI() {
        return Build.CPU_ABI;
    }

    private static int getCoresFromFileInfo(String fileLocation) {
        FileInputStream is = null;

        byte var3;
        try {
            is = new FileInputStream(fileLocation);
            BufferedReader buf = new BufferedReader(new InputStreamReader(is));
            String fileContents = buf.readLine();
            if (is != null) {
                is.close();
            }

            int var4 = getCoresFromFileString(fileContents);
            return var4;
        } catch (IOException var14) {
            var3 = -1;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException var13) {
                    Log.e("DeviceUtils", "close file stream", var13);
                }
            }

        }

        return var3;
    }

    private static int getCoresFromFileString(String str) {
        if (str != null && str.matches("0-[\\d]+$")) {
            int cores = Integer.valueOf(str.substring(2)) + 1;
            return cores;
        } else {
            return -1;
        }
    }

    private static int getCoresFromCPUFileList() {
        return (new File("/sys/devices/system/cpu")).listFiles(CPU_FILTER).length;
    }

    public static int getCPUMaxFreqKHz() {
        int maxFreq = -1;

        try {
            for(int i = 0; i < getNumberOfCPUCores(); ++i) {
                String filename = "/sys/devices/system/cpu/cpu" + i + "/cpufreq/cpuinfo_max_freq";
                File cpuInfoMaxFreqFile = new File(filename);
                if (cpuInfoMaxFreqFile.exists()) {
                    byte[] buffer = new byte[128];
                    FileInputStream stream = new FileInputStream(cpuInfoMaxFreqFile);

                    try {
                        stream.read(buffer);

                        int endIndex;
                        for(endIndex = 0; Character.isDigit(buffer[endIndex]) && endIndex < buffer.length; ++endIndex) {
                        }

                        String str = new String(buffer, 0, endIndex);
                        Integer freqBound = Integer.parseInt(str);
                        if (freqBound > maxFreq) {
                            maxFreq = freqBound;
                        }
                    } catch (NumberFormatException var20) {
                    } finally {
                        if (stream != null) {
                            stream.close();
                        }

                    }
                }
            }

            if (maxFreq == -1) {
                FileInputStream stream = new FileInputStream("/proc/cpuinfo");

                try {
                    int freqBound = parseFileForValue("cpu MHz", stream);
                    freqBound *= 1000;
                    if (freqBound > maxFreq) {
                        maxFreq = freqBound;
                    }
                } finally {
                    if (stream != null) {
                        stream.close();
                    }

                }
            }
        } catch (IOException var22) {
            maxFreq = -1;
        }

        return maxFreq;
    }

    private static int parseFileForValue(String textToMatch, FileInputStream stream) {
        byte[] buffer = new byte[1024];

        try {
            int length = stream.read(buffer);

            for(int i = 0; i < length; ++i) {
                if (buffer[i] == 10 || i == 0) {
                    if (buffer[i] == 10) {
                        ++i;
                    }

                    for(int j = i; j < length; ++j) {
                        int textIndex = j - i;
                        if (buffer[j] != textToMatch.charAt(textIndex)) {
                            break;
                        }

                        if (textIndex == textToMatch.length() - 1) {
                            return extractValue(buffer, j);
                        }
                    }
                }
            }
        } catch (IOException var7) {
        } catch (NumberFormatException var8) {
        }

        return -1;
    }

    private static int extractValue(byte[] buffer, int index) {
        while(true) {
            if (index < buffer.length && buffer[index] != 10) {
                if (!Character.isDigit(buffer[index])) {
                    ++index;
                    continue;
                }

                int start;
                for(start = index++; index < buffer.length && Character.isDigit(buffer[index]); ++index) {
                }

                String str = new String(buffer, 0, start, index - start);
                return Integer.parseInt(str);
            }

            return -1;
        }
    }
}
